package others;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EpubPack {

    public static void main(String[] args) throws IOException {
        File dir = new File("D:\\RocketMQ\\OEBPS\\");
        String[] list = dir.list((path, name) ->
            name.matches("text\\d+\\.html")
        );

        BufferedWriter writer = new BufferedWriter(new FileWriter(dir + "/all.html"));
        writer.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"font-size:1.250rem;\">\n" +
            "<head>" +
            "<title></title>\n" +
            "<base target=\"_blank\"></base>\n" +
            "<link href=\"flow0001.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
            "</head>\n" +
            "<body>");

        String contents = null;
        StringBuilder articles = new StringBuilder("<div id='article'>");
        Pattern pattern = Pattern.compile("<body.*>([\\s\\S]*?)</body>");
        Pattern pattern2 = Pattern.compile("<[a-zA-Z]+.*>([\\s\\S]*?)</[a-zA-Z]+>");
        for (String file : list) {
            byte[] bytes = Files.readAllBytes(Paths.get(dir.getAbsolutePath(), file));
            String content = new String(bytes, "UTF-8");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String body = matcher.group(1).trim();
                String[] split = body.split("\r?\n", 2);

                String first = split[0];
                Matcher matcher1 = pattern2.matcher(first);
                if (matcher1.find()) {
                    String title = matcher1.group(1);
                    if (title.equals("目录")) {
                        contents = "<div id='contents'>"
                            + body.replaceAll("href=\"(text\\d+\\.html)\"", " target=\"_self\" href=\"#$1\"") + "</div>";
                        writer.write(contents);
                        writer.write(articles.toString());
                        continue;
                    }
                }
                if (contents != null) {
                    writer.write("<div id=" + file + "></div>\r\n");
                    writer.write(body);
                } else {
                    articles.append("<div id=").append(file).append("></div>\r\n");
                    articles.append(body);
                }
            }
        }
        writer.write("</div></body>");
        writer.close();
    }


}
